<?php if(!defined('CALL')) exit('No direct script access allowed');

include_once('lib/utils.class.php');
include_once('lib/xtemplate.class.php');
include_once('lib/logger.class.php');

class vMessages
{

	public static function build_privateMessage($msg, $actor, $user, &$xtpl = null)
	{
		if($xtpl == null)
			$xtpl = new XTemplate('xtpl/main-messages.xtpl');
		
		$dts = date_format(date_create($msg['dt']), "d.m.Y H:i:s");
		$sender = ($actor->id == $msg['sender_id']) ? $actor : $user;
		
		$xtpl->assign('root', ROOT_URL);
		$xtpl->assign('username', $sender->props['username']);
		$xtpl->assign('user_id', $sender->id);
		$xtpl->assign('msg_id', $msg['id']);
		$xtpl->assign('date', $dts);
		$xtpl->assign('user_note', $sender->props['note']);
		$xtpl->assign('avatar', $sender->props['face']);
		$xtpl->assign('note', Utils::win2utf(str_replace("\n", "<br />\n", Utils::utf2win($msg['note']))));
		$xtpl->parse('root.PRIVATE.message');
		return $xtpl->text('root.PRIVATE.message');
	}
	
	public static function build_privateMessageLine($messages, $actor, $user)
	{
		$xtpl = new XTemplate('xtpl/main-messages.xtpl');
		self::common_assign($xtpl, $actor, $user);
		
		if($actor->id)
		{
			$xtpl->parse('root.PRIVATE.form');
		}
		
		$categ = 'PRIVATE';
		if(count($messages[$categ]) > 0)
		{
			foreach($messages[$categ] as $msg)
				self::build_privateMessage($msg, $actor, $user, $xtpl);
		}
		
		$xtpl->parse('root.PRIVATE');
		$xtpl->parse('root');
		return $xtpl->text('root');
	}
	
	public static function build_systemMessage($msg, $actor, &$xtpl = null)
	{
		if($xtpl == null)
			$xtpl = new XTemplate('xtpl/main-messages.xtpl');
		
		$dts = date_format(date_create($msg['dt']), "d.m.Y H:i:s");
		
		$xtpl->assign('root', ROOT_URL);
		$xtpl->assign('msg_id', $msg['id']);
		$xtpl->assign('date', $dts);
		$xtpl->assign('note', Utils::win2utf(str_replace("\n", "<br />\n", Utils::utf2win($msg['note']))));
		if($msg['status_u'] == 'NEW')
			$xtpl->parse('root.SYSTEM.message.new');
		else
			$xtpl->parse('root.SYSTEM.message.old');
		$xtpl->parse('root.SYSTEM.message');
		$html = $xtpl->text('root.SYSTEM.message');
		// Logger::Write(__FILE__." ".__FUNCTION__." line: ".__LINE__, $html);
		return $html;
	}
	
	public static function build_systemMessageLine($messages, $actor)
	{
		$xtpl = new XTemplate('xtpl/main-messages.xtpl');
		self::common_assign($xtpl, $actor, $user);
		
		foreach($messages as $list)
		{
			if(is_array($list))
				foreach($list as $msg)
					self::build_systemMessage($msg, $actor, $xtpl);
			else
				self::build_systemMessage($list, $actor, $xtpl);
		}
		
		$xtpl->parse('root.SYSTEM');
		$xtpl->parse('root');
		return $xtpl->text('root');
	}
	
	private static function common_assign(&$xtpl, $actor, $user)
	{
		$xtpl->assign('root', ROOT_URL);
		$xtpl->assign('username', $user->props['username']);
	}
	
}